package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logc"
	"microdemo/service/order/internal/svc"
	"microdemo/service/order/order"
	"microdemo/service/user/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderLogic {
	return &GetOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetOrderLogic) GetOrder(in *order.OrderIdRequest) (*order.OrderResponse, error) {
	// 调用 user rpc，判断订单对应用户信息是否存在
	userResponse, err := l.svcCtx.UserRpc.GetUser(context.Background(), &user.IdRequest{
		Id: "1",
	})
	if err != nil {
		return nil, err
	} else {
		marshal, _ := json.Marshal(userResponse)
		// logc 是对 logx 的封装，可以带上 context 进行日志打印
		logc.Info(context.Background(), fmt.Sprintf("用户信息：%s", marshal))
	}
	// 直接数据库查询用户信息
	one, err := l.svcCtx.UserModel.FindOne(l.ctx, 1)
	if err != nil {
		return nil, err
	}
	marshal, err := json.Marshal(one)
	if err != nil {
		return nil, err
	}
	// 查询用户信息并返回
	return &order.OrderResponse{
		Id: "order001",
		No: fmt.Sprintf("订单信息查询接口返回。查询 id 为 1 的用户信息为：%s", marshal),
	}, nil
}
